package com.example.demothree.controller;
import com.example.demothree.bean.Employee;
import com.example.demothree.bean.Managers;
import com.example.demothree.bean.UserName;
import com.example.demothree.dao.UserNameDao;
import com.example.demothree.service.LoginService;
import com.example.demothree.util.MyMD5Util;
import jdk.nashorn.internal.runtime.regexp.joni.Config;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicInteger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("login")
public class LoginController {

    @Resource
    private LoginService loginService;

    //thymeleaf全局的储存信息的空间
    @Resource
    private ThymeleafViewResolver thymeleafViewResolver ;

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 时间间隔（分钟）
     */
    private static final int time_interval = 10;
    /**
     * 登录失败重试次数上限
     */
    private static final int failed_retry_times = 5;
    /**
     * redis记录用户登录失败次数key
     */
    private static final String user_login_failed_count = "user_login_failed_count:";

    private Employee employee;
    private Managers managers;
    private UserName userName;
    //    @Qualifier(value = "UserServiceImpl")
    // 接口注入，注入的是接口的实现类，注入之后就可以通过该对象调用接口实现的方法，如果接口有多个实现方类可以配合@Qualifier(value=“类名”)注解实现注入
//    @PostMapping("index")


    @RequestMapping( "login")
    @ResponseBody
    public String index(Model model,HttpServletRequest req, HttpServletResponse res) throws IOException, NoSuchAlgorithmException {//req接收前端数据，res向前端传输数据
        //req接收前端数据，res向前端传输数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        String key = user_login_failed_count + username;
        RedisAtomicInteger counter = getRedisCounter(key);

        loginService.outLogin(req);

        int date1 = 0;
        managers = loginService.adminname(username);
        if (managers == null) {
            employee = loginService.loginname(username);
            if (counter.get() >= failed_retry_times) {
                date1 = Math.toIntExact(counter.getExpire());
                //校验密码
            }else if (employee != null && MyMD5Util.validPassword(password, employee.getPassword()) && username.equals(employee.getName())){
                //成功清零
                stringRedisTemplate.delete(key);
                //
                req.getSession().setAttribute("username",employee.getName());
                thymeleafViewResolver.addStaticVariable("employee",employee);
                date1 = 1000;
            }else {
                // 失败次数 + 1
                counter.getAndIncrement();
                date1 = 5-counter.get()-10;
            }
        }else {
            if (counter.get() >= failed_retry_times) {
                System.out.println("登录已达上限，请"+counter.getExpire()+"秒后重试!");
                date1 = Math.toIntExact(counter.getExpire());
                //校验密码
            }else if (managers != null && MyMD5Util.validPassword(password, managers.getPassword()) && username.equals(managers.getName())){
                //成功清零
                stringRedisTemplate.delete(key);
                //
                req.getSession().setAttribute("username",managers.getName());

                thymeleafViewResolver.addStaticVariable("managers",managers);
                date1 = 1001;
            }else {
                // 失败次数 + 1
                counter.getAndIncrement();
                System.out.println("密码或用户名错误！"+2);
                date1 = 5-counter.get()-10;
            }
        }
        res.getWriter().print(date1);
        return null;
    }

    @RequestMapping("index")
    public String index1() {
        return "index";
    }
    @RequestMapping("addyh")
    public String addyh(Model model) {
        int a = 1;
        System.out.println(a+"uiioo");
        model.addAttribute("a", a);
        return "addyh";
    }
    @GetMapping("addyh/{name}")
    public String addyhzc(@PathVariable String name,Model model) {
            managers = loginService.adminname(name);
            if (managers == null) {
                employee = loginService.loginname(name);
                model.addAttribute("reviseUser", employee);
                return "addyh";
            } else {
                model.addAttribute("reviseUser", managers);
                return "addgly";
            }
    }
    //注册
    @RequestMapping("addyhzc")
    @ResponseBody
    public String addyhzc(HttpServletRequest request,HttpServletResponse response) throws IOException, NoSuchAlgorithmException {
        System.out.println("993|||||||");

        String encryptedPwd = null;

        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String age = request.getParameter("age");
        String gender = request.getParameter("gender");
        String phone = request.getParameter("phone");
        String password = request.getParameter("password");
        //加密
        encryptedPwd = MyMD5Util.getEncryptedPwd(password);

//        Employee employee1 = loginService.findByName(name);
//        userName = loginService.findUserNameByName(name);
        employee = loginService.findemployeeId(Long.valueOf(id));
        System.out.println(employee+"|||||||"+Long.valueOf(id));
        int addyh = 0;
//        if (userName == null) {
            if (employee != null){
                //修改
                employee = loginService.findbyId(Long.valueOf(id));
            }else {
                //添加
                employee = new Employee();
            }
            employee.setName(name);
            employee.setAge(Long.valueOf(age));
            employee.setGender(gender);
            employee.setPhone(phone);
            employee.setPassword(encryptedPwd);
            try {
                if (employee != null) {
                    //修改用户
                    loginService.upyh(employee, Long.valueOf(id));
                    addyh = -100;
                }else {
                    //添加用户
                    loginService.addyh(employee);
                    addyh = 100;
                }
            } catch (Exception e){
                addyh = 200;
                e.printStackTrace();
            }
//        }
        response.getWriter().print(addyh);
        return null;
    }

//
    private RedisAtomicInteger getRedisCounter(String key) {
        RedisAtomicInteger counter = new RedisAtomicInteger(key, stringRedisTemplate.getConnectionFactory());
        if (counter.get() == 0) {
            // 设置过期时间，10分钟
            counter.expire(time_interval, TimeUnit.MINUTES);
        }
        return counter;
    }

}
